/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cse.p2p.parser;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * This class contains all infomation of a piece. This info will be sent from the 
 * client to peer when request a piece
 * 
 * @author TrungHieu
 */
public class PieceInfo {

	private int fileID;
	private int pieceID;
	private static final String KEY_FILE_ID = "file_id";
	private static final String KEY_PIECE_ID = "piece_id";

	public PieceInfo( int fileID, int pieceID ) {
		this.fileID = fileID;
		this.pieceID = pieceID;
	}

	public int getFileID() {
		return fileID;
	}

	public int getPieceID() {
		return pieceID;
	}

	@Override
	public String toString() {
		try {
			JSONObject jsObj = new JSONObject();
			jsObj.put( KEY_FILE_ID, this.fileID );
			jsObj.put( KEY_PIECE_ID, this.pieceID );
			return jsObj.toString();
		}
		catch ( JSONException e ) {
			return "";
		}
	}

	public static PieceInfo fromString( String input ) {
		try {
			JSONObject jsObj = new JSONObject( input );
			return new PieceInfo( jsObj.getInt( KEY_FILE_ID ),
								  jsObj.getInt( KEY_PIECE_ID ) );
		}
		catch ( JSONException e ) {
			return null;
		}
	}
}
